package test.administrator.example.com.mvptest1.framework.support.viewstate.lce.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;

import test.administrator.example.com.mvptest1.framework.MvpPresenter;
import test.administrator.example.com.mvptest1.framework.lce.MvpLceView;
import test.administrator.example.com.mvptest1.framework.lce.impl.activity.MvpLceActivity;
import test.administrator.example.com.mvptest1.framework.support.activity.ActivityMvpDelegate;
import test.administrator.example.com.mvptest1.framework.support.viewstate.MvpViewStateDelegateCallback;
import test.administrator.example.com.mvptest1.framework.support.viewstate.activity.ActivityMvpViewStateDelegateImpl;
import test.administrator.example.com.mvptest1.framework.support.viewstate.lce.LceViewState;

public abstract class MvpLceViewStateActivity<M, V extends MvpLceView<M>, P extends MvpPresenter<V>>
		extends MvpLceActivity<M, V, P>
		implements MvpLceView<M>, MvpViewStateDelegateCallback<V, P, LceViewState<M, V>> {

	//LCE状态
	protected LceViewState<M, V> viewState;

	//是否正在恢复
	protected boolean restoringViewState = false;

	@Override
	protected ActivityMvpDelegate<V, P> getMvpDelegate() {
		if (mvpDelegate == null) {
			mvpDelegate = new ActivityMvpViewStateDelegateImpl<>(this, this, true);
		}
		return mvpDelegate;
	}

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (viewState == null) {
			viewState = createViewState();
		}
	}

	@Override
	public LceViewState<M, V> getViewState() {
		return viewState;
	}

	@Override
	public void setViewState(LceViewState<M, V> viewState) {
		this.viewState = viewState;
	}

	@Override
	public void setRestoringViewState(boolean restoringViewState) {
		this.restoringViewState = restoringViewState;
	}

	@Override
	public boolean isRestoringViewState() {
		return restoringViewState;
	}

	@Override
	public void onNewViewStateInstance() {
		loadData(false);
	}

	@Override
	public void onViewStateInstanceRestored(boolean instanceStateRetainedInMemory) {
		if (!instanceStateRetainedInMemory && viewState.isLoadingState()) {
			loadData(viewState.isPullToRefreshLoadingState());
		}
	}

	@Override
	public void showContent() {
		super.showContent();
		viewState.setStateShowContent(getData());
	}

	@Override
	public void showError(Throwable e, boolean pullToRefresh) {
		super.showError(e, pullToRefresh);
		viewState.setStateShowError(e, pullToRefresh);
	}

	@Override
	public void showLoading(boolean pullToRefresh) {
		super.showLoading(pullToRefresh);
		viewState.setStateShowLoading(pullToRefresh);
	}

	public abstract M getData();
}
